#ifndef _NETWORKHANDLER_
#define _NETWORKHANDLER_

#include "Networking.hpp"
#include <SFML/Network.hpp>
#include <iostream>

class NetworkHandler {
private:
    static NetworkHandler* currentInstance;

    sf::IpAddress address;
    sf::UdpSocket socket;

    unsigned short in_port;
    unsigned short out_port;

    class ServerClock : public MessageQueue::ServerTime {
    public:
        uint32_t serverTime;
        sf::Clock serverTimer;

		ServerClock(){
			serverTime = 0;
			serverTimer.restart();
		}

        virtual uint32_t getTime() {
            return serverTime + serverTimer.getElapsedTime().asMilliseconds();
        }
    };

    byte clientIndex;
public:
    ServerClock serverTime;

    static NetworkHandler* getInstance();

    MessageQueue* outQueue;
	MessageQueue* inQueue;

    NetworkHandler(std::string sAddr, unsigned short sPort);
    void bind(unsigned short port);
    
	MessageIterator& addMessage(Message::MessageCode code, void* data);
    bool sendMessages();
    bool forceSendMessages();

    void setServerTime(uint32_t time);
    void setClientIndex(byte index);

    MessageQueue* getServerMessagesWait(unsigned int timeout);
    MessageQueue* getServerMessages();

    void closeConnection();

    ~NetworkHandler();

};

#endif